#Duke University
#2 November 2011
#Jordan Besnoff
#
#This program is used to determine RSSI as a function of distance. The program
#will look for a specific tag, the user will input the distance, and then
#record the RSSI for a set amount of time, and average the result. This will
#be saved to a text file

import sys, time, string, lib_M5e_VA
from numpy import *
from scipy import *

#File for data logging
data_file = open('data_file.txt','a')


#Reader initialization
def P1(M5e):
    M5e.ChangeAntennaPorts(1,1)
    return 'AntPort1'

def P2(M5e):
    M5e.ChangeAntennaPorts(2,2)
    return 'AntPort2'

def Store(stuff):
    global ant,ids,rssi,data_line,tag_reads
    ant, ids, rssi = stuff
    data_line = [ids,rssi,time.asctime(time.localtime()),repr(time.time()),ant]
    tag_reads.append(data_line)

#---------------Reader parameters-----------------#
Power = 3000
read_time = 10
#-------------------------------------------------#

print "\nInitializing Reader."
r = lib_M5e_VA.M5e(readPwr=Power)
print "Reader initialized, ready to begin tag search."


flag = True
while flag:
    #Ask user for parameters and perform RSSI measurement
    tag = raw_input('Enter ID of tag (type Q to quit): ')

    if tag == 'Q':
        flag = False

    else:
        dist = raw_input('Enter current distance from tag in meters: ')
        print "\nSearching for specified tag. Do not move antenna until completion"
        
        tag_reads = []

        q = lib_M5e_VA.M5e_Poller(r, antfuncs=[P1], callbacks=[Store])

        q.query_mode()

        t0 = time.time()
        while time.time() - t0 < read_time:
            blah = 0

        q.stop()

        if tag_reads == []:
            print "\nNo tags found!"

        else:
            #Reformat tag
            tmp = []
            for i in range(0,len(tag),4):
                tmp.append(chr(int(tag[i:(i+4)],16)))
            tag = ''.join(tmp)
                    
            #Remove extraneous tags
            tag_reads = array(tag_reads)
                    
            rem = []
            for x in range(0,len(tag_reads)):

                if tag_reads[x,0] != tag:
                    rem.append(x)

            tag_reads = delete(tag_reads,rem,0)

            #If tag not found (only "spurious" tags)
            if len(tag_reads) == 0:
                print "\nTag not found!"

            else:  #Tag was found, average the RSSI values
                #Show tag reads
                print tag_reads

                #Extract and average the RSSI values
                RSSI_val = []
                for x in tag_reads[:,1]:
                    RSSI_val.append(float(x))

                RSSI_val = array(RSSI_val)

                RSSI_avg = sum(RSSI_val) / len(RSSI_val)

                print "\nThe average RSSI value is:",RSSI_avg
                        
                #Store values
                data_file.write(str(dist)+' '+str(RSSI_avg)+'\n')
                print ' '
            
data_file.close()






